﻿using AutoMapper;
using Dapper;
using DocumentFormat.OpenXml.EMMA;
using MediatR;
using MyMES.Domain.zmc;
using MyMES.Domain.zyy;
using MyMES.Error;
using MyMES.Infrastructure;
using MyMES.Infrastructure.Interface;
using MyMES.Writer.API.Application.Commends.Productionorderss;
using MySqlX.XDevAPI.Common;
using System.Data;

namespace MyMES.Writer.API.Application.CommendHandlers.Productionorderss
{
    public class CreateProductionordersCommendHandlers : IRequestHandler<CreateProductionordersCommends, APIResult<Productionorders>>
    {

        private readonly IBaseRepository<Productionorders> productionsRepository;
        private readonly IMapper mapper;
        public DatabaseContext db;

        public CreateProductionordersCommendHandlers(IBaseRepository<Productionorders> productionsRepository, IMapper mapper, DatabaseContext db)
        {
            this.productionsRepository = productionsRepository;
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 生产工单---新
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<APIResult<Productionorders>> Handle(CreateProductionordersCommends request, CancellationToken cancellationToken)
        {

            /*     try
                 {



                     APIResult<Productionorders> result = new APIResult<Productionorders>();
                     result.Code = APIEnum.添加成功;
                     result.Msg = "添加成功";

                      string sql = @"INSERT INTO Productionorders (
                                ProductionordersNo, ProductionordersName, Topic, 
                                Head, Department, ProductionordersStatus, 
                                MId, WorkOrderId,PlanStartTime,PlanEndTime,yield,Remark,IsDelete,ProductionordersTime,ProcessID
                            ) VALUES (
                                @ProductionordersNo, @ProductionordersName, @Topic, 
                                @Head, @Department, @ProductionordersStatus, 
                                @MId, @WorkOrderId,@PlanStartTime,@PlanEndTime,@yield,@Remark,@IsDelete,ProductionordersTime,@ProcessID
                            );"
                     ;
                     var model = mapper.Map<Productionorders>(request);
                 foreach (var item in )
                 {
                     var shuju = new woekderProess();
                     shuju.ProcessID = model.ProcessID;
                     shuju.ProductionordersId = item;
                     await productionsRepository.Insert(model, sql);
                 }



                     return  result;

                 }
                 catch (Exception ex)
                 {


                     // 记录日志或处理异常
                     throw new Exception("创建生产工单失败，事务已回滚", ex);
                 }
             }*/


            var result = new APIResult<Productionorders>();
         
      
            // 确保ProcessIDs不为null
            request.ProcessIDs ??= new List<int>();
            using (var connection = db.Connection)
            {
                // 统一管理连接状态
                if (connection.State != ConnectionState.Open)
                {
                    connection.Open();
                }
                using (var transaction = db.Connection.BeginTransaction())
                {
                    try
                    {
                        // 映射生产工单实体
                        var productionOrder = mapper.Map<Productionorders>(request);

                        // 构建插入SQL（移除了ProcessID字段）
                        var insertSql = @"
                        INSERT INTO Productionorders (
                            ProductionordersNo, ProductionordersName, Topic, 
                            Head, Department, ProductionordersStatus, 
                            MId, WorkOrderId, PlanStartTime, PlanEndTime, 
                            yield, Remark, IsDelete, ProductionordersTime
                        ) VALUES (
                            @ProductionordersNo, @ProductionordersName, @Topic, 
                            @Head, @Department, @ProductionordersStatus, 
                            @MId, @WorkOrderId, @PlanStartTime, @PlanEndTime, 
                            @yield, @Remark, @IsDelete, @ProductionordersTime
                        );
                        SELECT LAST_INSERT_ID();";

                        // 执行插入并获取工单ID
                        var productionOrderId = await db.Connection.ExecuteScalarAsync<int>(
                            insertSql,
                            productionOrder,
                            transaction);

                        // 插入中间表数据
                        if (request.ProcessIDs.Any())
                        {
                            const string middleTableSql = @"
                            INSERT INTO woekderProess 
                                (ProductionordersId, ProcessID, Zt, Goodproduct, Notproduct, Fzr, CreateTime,WorkOrderId,MId,IsDelete)
                            VALUES 
                                (@ProductionOrderId, @ProcessID, @Zt, @Goodproduct, @Notproduct, @Fzr, @CreateTime,@WorkOrderId, @MId,@IsDelete)";

                            foreach (var processId in request.ProcessIDs)
                            {
                                await db.Connection.ExecuteAsync(
                                    middleTableSql,
                                    new
                                    {
                                        ProductionOrderId = productionOrderId,
                                        ProcessID = processId,
                                        Zt = false,          // 默认状态为未开始
                                        Goodproduct = 0,     // 初始良品数
                                        Notproduct = 0,      // 初始不良品数
                                        Fzr = productionOrder.Head,  // 空负责人
                                        CreateTime = DateTime.Now,
                                        WorkOrderId = productionOrder.WorkOrderId,
                                        MId = productionOrder.MId,
                                        IsDelete = false
                                    },
                                    transaction);
                            }
                        }

                        transaction.Commit();

                        // 使用同一连接查询（根据图片修正方法名）
                        var newOrder = await connection.QueryFirstOrDefaultAsync<Productionorders>(
                            "SELECT * FROM Productionorders WHERE ProductionordersId = @id",
                            new { id = productionOrderId });

                        result.Code = APIEnum.添加成功;
                        result.Msg = $"工单创建成功，关联工序数：{request.ProcessIDs.Count}";
                        result.data = newOrder;
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        // _logger.LogError(ex, "创建生产工单失败");
                        throw new Exception("创建生产工单失败，事务已回滚", ex);
                    }
                }
            }
        

            return result;
        }
    


}
 
}
